package com.doudi.product;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;

/**
 * 
 * @author lifei
 *
 */
public class TxtReader {
	public void readFromTxtEachLine(String ip, String db, String filePath, int startLine, int endLine, int tableCount)
			throws IOException {
		File file = new File(filePath);
		BufferedInputStream fis = new BufferedInputStream(new FileInputStream(file));
		BufferedReader reader = new BufferedReader(new InputStreamReader(fis, "utf-8"), 5 * 1024 * 1024);//缓存5M

		String line = "";
		int count = 0;
		String sql = "";
		Connection conn = null;
		Statement stmt = null;
		try {
			Class.forName("com.mysql.jdbc.Driver");
			System.out.println("Connecting to a selected database...");
			conn = DriverManager.getConnection(DBConfig.getDB_URL(ip, db), DBConfig.USER, DBConfig.PASS);
			System.out.println("Connected database successfully...");
			stmt = conn.createStatement();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		while ((line = reader.readLine()) != null && count <= endLine) {
			System.out.println(count + "每行：" + line);
			if (count < startLine) {
				count++;
				// System.out.println("数据已存在，不执行插入");
			} else {
				sql = InsertSql.generateSql(line, tableCount);
				Push2DB.pushProduct2DB(conn, stmt, sql);
				count++;
			}
		}
	}

	public static void main(String[] args) throws IOException {
		String str = args[0];
		String[] strArr = null;

		try {
			strArr = str.split("-");
		} catch (Exception e) {
			System.out.println("ip-db-filePath-startLine-endLine-tableCount");
		}

		String ip = strArr[0];
		String db = strArr[1];
		String filePath = strArr[2];
		int startLine = Integer.valueOf(strArr[3]);
		int endLine = Integer.valueOf(strArr[4]);
		int tableCount = Integer.valueOf(strArr[5]);
		new TxtReader().readFromTxtEachLine(ip, db, filePath, startLine, endLine, tableCount);
	}
}
